#include "abstractlistmodel.h"

AbstractListModel::AbstractListModel(QObject *parent) : QAbstractListModel(parent) {
}

void AbstractListModel::addListItem(AbstractListItem *item) {
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_abstractList.append(item);
    m_hashList[item->name()] = item;
    endInsertRows();
    setCount(m_count + 1);
}

void AbstractListModel::addListItems(QList<AbstractListItem *> list) {
    for (auto str : list) {
        if (str) {
            addListItem(str);
        }
    }
}

void AbstractListModel::removeListItemByIndex(int index) {
    if (index >= m_count || index < 0)
        return;
    beginRemoveRows(QModelIndex(), index, index);
    m_abstractList.removeAt(index);
    endRemoveRows();
    setCount(m_count - 1);
}

int AbstractListModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return m_abstractList.count();
}

QVariant AbstractListModel::data(const QModelIndex &index, int role) const {
    if (index.row() < 0 || index.row() >= m_abstractList.count())
        return QVariant();
    if (role == model)
        return QVariant::fromValue(m_abstractList[index.row()]);
    return QVariant();
}

int AbstractListModel::count() const {
    return m_count;
}

AbstractListItem *AbstractListModel::hash_list(QString str) {
    return m_hashList[str];
}

void AbstractListModel::setCount(int count) {
    if (m_count == count)
        return;

    m_count = count;
    emit countChanged(m_count);
}

QHash<int, QByteArray> AbstractListModel::roleNames() const {

    return QHash<int, QByteArray>{ { model, "model1x" } };
}
